package com.mishow.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.mishow.adapter.StarResultFragmentAdapter.OnItemClickListener;
import android.widget.ListView;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.StarDetailsActivity;
import com.mishow.adapter.StarResultFragmentAdapter;
import com.mishow.adapter.StarResultFragmentAdapter.OnClickInterface;
import com.mishow.bean.ChatVO;
import com.mishow.fragment.base.BaseFragment;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.ChatResponse.Result;
import com.mishow.request.response.ChatResponse;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.EmptyDataLayout;
import com.mishow.widget.MyRecycleView;
/**
 * 
 * 作者：wei.miao <br/>
 * 描述：星秀-关注-最热-最新
 */
public class StarResultFragment extends BaseFragment implements OnRefreshListener, PullPushRefreshLayout.OnLoadListener{

	private Context mContext;
	
	/** 下拉刷新 **/
	private PullPushRefreshLayout refresh_layout;
	/** 数据为空 **/
	private EmptyDataLayout empty_start;
	/** 星秀列表 **/
	private MyRecycleView list_star;
	
	private ArrayList<ChatVO> mChats;
	
	private View view;
	
	private StarResultFragmentAdapter mStartResultAdapter;
	
	/** 星秀状态(0=关注 1=最热 2=最新)  **/
	private int starStatus;
	
	/** 关注 **/
	public static final int STATUS_ALL = 0;
	/** 最热 **/
	public static final int STATUS_RECRUIT = 1; 
	/** 最新 **/
	public static final int STATUS_PAST= 2; 
	
	private int pageNo = 1;
	
	private int pageSize = 10;
	
	
	/** 列表总条数 **/
	private int total;
	/** 是否正在网络请求中默认为false **/
	private boolean isReflesh;
	/** 刷新操作 **/
	public static final int ACTION_REFRESH = 1;
	/** 加载更多操作 **/
	public static final int ACTION_LOAD_MORE = 2;
	
	private SharedPreferencesUtil preferencesUtil;
	
	public static StarResultFragment newInstance() {
		
		StarResultFragment fragment = new StarResultFragment();
		return fragment;
	}
	
	public static StarResultFragment newInstance(int status) {
		
		Bundle args = new Bundle();
		args.putInt("", status);
		StarResultFragment fragment = new StarResultFragment();
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		this.mContext = context;
	}
	
	@Override  
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){  
        super.onCreateView(inflater, container, savedInstanceState);  
        if (view == null) {
			view = inflater.inflate(R.layout.item_star_tab, container, false);
		} else {
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}

		}
		initView(view);
		initData();
		setAttribute();
		return view;
    } 
	
	/**
	 * 初始化View
	 * @param view
	 */
	private void initView(View view){
		
		refresh_layout = (PullPushRefreshLayout)view.findViewById(R.id.refreshLayout_start);
		empty_start = (EmptyDataLayout)view.findViewById(R.id.empty_start);
		list_star = (MyRecycleView)view.findViewById(R.id.list_star);
	}
	/**
	 * 初始化数据
	 */
	private void initData(){
    	
		mChats = new ArrayList<ChatVO>();
    	preferencesUtil = new SharedPreferencesUtil(mContext);
    	Bundle args = getArguments();
		if (args != null) {
			starStatus = args.getInt("releaseStatus");
		}
		mStartResultAdapter = new StarResultFragmentAdapter(getActivity(), mChats);
    }
	
	/**
	 * 设置控件属性
	 */
	private void setAttribute(){
		
		refresh_layout.setOnRefreshListener(this);
		refresh_layout.setOnLoadListener(this);
		
		LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);//支付横向、纵向
		//设置布局管理器 
		list_star.setLayoutManager(layoutManager);
		list_star.setAdapter(mStartResultAdapter);
		
		mStartResultAdapter.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onLongClick(int position) {}
			
			@Override
			public void onClick(int position) {
				ChatVO chatVO = mChats.get(position);
				StarDetailsActivity.intoActivity(mContext, chatVO.getId()+"");
			}
		});
		mStartResultAdapter.setOnClickInterface(onClickInterface);
		
		onRefresh();
	}
	
	@Override
	public void onLoad() {
		if (total > mChats.size()) {
			pageNo++;
			getMyStartFromApi(ACTION_LOAD_MORE);
		} else {
			loadCompleted();
		}
	}

	@Override
	public void onRefresh() {
		pageNo = 1;
		getMyStartFromApi(ACTION_REFRESH);
	}
	
	/**
	 * 服务端获取星秀列表
	 * @param action 区分刷新或加载更多
	 */
	private void getMyStartFromApi(final int action) {

		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		if(isReflesh){
			return ;
		}
		isReflesh = true;
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("pageNo", pageNo+"");
		params.put("pageSize", pageSize+"");

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.GET_QUERY_CHATPAGE);
		OnResponseListener<ChatResponse> listener = new OnResponseListener<ChatResponse>(mContext) {

			@Override
			public void onSuccess(ChatResponse response) {

				Result result = response.getBody().getResult();
				
				ArrayList<ChatVO> dataList = result.getDataList();
				
				if (dataList != null && dataList.size() > 0) {
					total = response.getBody().getResult().getTotal();
					if (action == ACTION_REFRESH) {
						handlerRefresh(dataList);
					} else if (action == ACTION_LOAD_MORE) {
						handleLoadMore(dataList);
					}
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
				if (action == ACTION_LOAD_MORE) {
					pageNo--;
				}
			}

			@Override
			public void onCompleted() {
				isReflesh = false;
				dismissProgress();
				loadCompleted();
			}
		};
		executeRequest(new FastJsonRequest<ChatResponse>(
				Request.Method.POST, postUrl, ChatResponse.class,
				listener, listener).setParams(lastParams));

	}
	
	/**
	 * 刷新后的数据
	 * @param results
	 */
	private void handlerRefresh(ArrayList<ChatVO> results) {
		if (results == null || results.isEmpty()) {
			//mChats.clear();
			//mStartResultAdapter.notifyDataSetChanged();
			empty_start.setVisibility(View.VISIBLE);
			refresh_layout.setVisibility(View.GONE);
		} else {
			empty_start.setVisibility(View.GONE);
			refresh_layout.setVisibility(View.VISIBLE);
			mChats.clear();
			mChats.addAll(results);
			mStartResultAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载更多数据 
	 * @param results
	 */
	private void handleLoadMore(ArrayList<ChatVO> results) {
		if (results != null && !results.isEmpty()) {
			mChats.addAll(results);
			mStartResultAdapter.notifyDataSetChanged();
		}
	}
	
	/**
	 * 加载完成
	 */
	private void loadCompleted() {

		refresh_layout.setRefreshing(false);
		refresh_layout.setLoading(false);
		// 获取到全部数据后，则隐藏加载更多
		if (total > mChats.size()) {
			refresh_layout.setCanLoadMore(true);
		} else {
			refresh_layout.setCanLoadMore(false);
		}
	}
	
	
	private OnClickInterface onClickInterface = new OnClickInterface() {
		
		@Override
		public void onClickLikeShare() {
			ToastUtil.show(mContext, "分享转发");
		}
		
		@Override
		public void onClickLike(String chatId) {
			doSaveLiked(chatId);
		}
		
		@Override
		public void onClickFocus(String userId) {
			doFocus(userId);
		}

		@Override
		public void onClickComment(String comment, String commentReviewersId,
				String commentChatId, String commentRespondentId,
				String commentType) {
			if (comment != null && !comment.equals("")) {
				doSaveComment(comment,commentReviewersId,commentChatId,commentRespondentId,commentType);
			}else{
				
				ToastUtil.show(mContext, "请输入评论信息");
			}
		}

		
	};
	
	
	/**
	 * 添加评论
	 */
	private void doSaveComment(String comment, String commentReviewersId,
			String commentChatId, String commentRespondentId,
			String commentType){
		
		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("commentText", comment);
		params.put("commentReviewersId", commentReviewersId);
		params.put("commentChatId", commentChatId);
		params.put("commentRespondentId", commentRespondentId);
		params.put("commentType", commentType);

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.SAVE_COMMENT);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				//刷新数据
				onRefresh();
				
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(
				Request.Method.POST, postUrl, Response.class,
				listener, listener).setParams(lastParams));
		
	}
	
	
	/**
	 * 关注
	 */
	private void doFocus(String userId){
		
		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("concernId", userId);//关注ID
		params.put("concernUserId", preferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.SAVE_CONCERN);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(
				Request.Method.POST, postUrl, Response.class,
				listener, listener).setParams(lastParams));
		
	}
	
	/**
	 * 点赞
	 */
	private void doSaveLiked(String chatId){
		
		if (!AndroidUtil.isNetworkAvailable(mContext)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("chatId", chatId);
		params.put("userId", preferencesUtil.getUserId());

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(mContext,HttpUrlConstant.SAVE_LIKED);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(mContext) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				onRefresh();
				//刷新数据
				//mStartResultAdapter.notifyDataSetChanged();
				
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(
				Request.Method.POST, postUrl, Response.class,
				listener, listener).setParams(lastParams));
		
	}
	
}
